package br.com.dataphonebr.selectListener;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class CustomOnItemSelectedListener<T> implements OnItemSelectedListener {
	
	protected Context context;
	private ArrayAdapter<T> dataAdapter;
	
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Toast.makeText(parent.getContext(), "Item selecionado : " + parent.getItemAtPosition(pos).toString(),Toast.LENGTH_SHORT).show();
    }
 
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }
    
    public void createAdapter(List<T> list, Spinner spinner){
        dataAdapter = new ArrayAdapter<T>(context, android.R.layout.simple_spinner_item, list);
        createAdapter(dataAdapter, spinner);
    }

    public void createAdapter(T[] list, Spinner spinner){
    	dataAdapter = new ArrayAdapter<T>(context, android.R.layout.simple_spinner_item, list);
    	createAdapter(dataAdapter, spinner);
    }
    
    private void createAdapter(ArrayAdapter<T> dataAdapter, Spinner spinner){
    	dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner.setAdapter(dataAdapter);
    }
    
    public ArrayAdapter<T> getDataAdapter() {
		return dataAdapter;
	}
    
    public int getSelectedItem(T entity){
		for (int i=0; i < dataAdapter.getCount(); i++){
			T t = dataAdapter.getItem(i);
			if (t.equals(entity))
				return i;
		}
		return 0;
    }
    
}
